<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能刷题系统</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="assets/js/tailwind.min.js"></script>
    <!-- 本地引用pdf.min.js -->
    <script src="assets/js/pdf.min.js"></script>
    <!-- 本地引用font-awesome.min.css-->
    <link href="assets/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#FF7D00',
                        success: '#00B42A',
                        danger: '#F53F3F',
                        neutral: {
                            100: '#F5F7FA',
                            200: '#E5E6EB',
                            300: '#C9CDD4',
                            400: '#86909C',
                            500: '#4E5969',
                            600: '#272E3B',
                            700: '#1D2129',
                        },
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
</head>
<body class="bg-neutral-100 font-inter min-h-screen">
    <div class="w-full px-4 py-8">
        <!-- 主内容区域 -->
        <main class="bg-white rounded-2xl shadow-lg p-6 md:p-8 mb-8">
            <!-- 开始界面 -->
            <div id="start-screen" class="text-center py-12">
                <!-- 头部区域 -->
                <header class="mb-10 text-center">
                    <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-neutral-700 mb-3">
                        🎓 PDF刷题系统
                    </h1>
                </header>
                <div class="max-w-md mx-auto">
                    <div class="mb-6">
                        <label for="pdf-upload" class="block text-left text-neutral-600 font-medium mb-2">
                            📄 上传PDF题目
                        </label>
                        <input type="file" id="pdf-upload" accept=".pdf" class="w-full px-4 py-3 rounded-lg border border-neutral-300 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all">
                    </div>
                    
                    <div class="mb-6">
                        <label for="total-questions-input" class="block text-left text-neutral-600 font-medium mb-2">
                            📝 总题数
                        </label>
                        <input type="number" id="total-questions-input" min="1" value="15" class="w-full px-4 py-3 rounded-lg border border-neutral-300 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all">
                    </div>
                    
                    <div class="mb-6">
                        <label for="start-question-input" class="block text-left text-neutral-600 font-medium mb-2">
                            📌 开始题号
                        </label>
                        <input type="number" id="start-question-input" min="1" value="1" class="w-full px-4 py-3 rounded-lg border border-neutral-300 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all">
                    </div>
                    
                    <button id="start-btn" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-6 rounded-lg transition-all duration-300 hover:shadow-lg hover:-translate-y-1 flex items-center justify-center" disabled>
                        ▶️ 开始刷题
                    </button>
                </div>
            </div>

            <!-- 做题界面 -->
            <div id="quiz-screen" class="hidden">
                <div class="flex flex-col md:flex-row gap-6">
                    <!-- 左侧：题目区域 -->
                    <div class="md:w-3/4 relative">
                        <!-- PDF容器 -->
                        <div id="pdf-container" class="w-full h-[calc(100vh-200px)] bg-neutral-50 rounded-xl mb-6 overflow-auto border border-neutral-200">
                            <div class="flex items-center justify-center h-full text-neutral-400">
                                <span class="animate-spin mr-2">🔄</span>加载中...
                            </div>
                        </div>
                        
                        <!-- PDF翻页控制 -->
                        <div class="flex justify-between items-center mt-4">
                            <button id="prev-pdf-btn" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 font-medium transition-all duration-300 hover:shadow-lg hover:-translate-y-1 disabled:opacity-50 disabled:cursor-not-allowed flex items-center" disabled>
                                ← 上一页
                            </button>
                            
                            <div class="flex items-center">
                                <span class="text-neutral-500 mr-2">第</span>
                                <input type="number" id="page-num-input" min="1" value="1" class="w-16 px-3 py-2 rounded-lg border border-neutral-300 text-center focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all">
                                <span class="text-neutral-500 ml-2">页，共</span>
                                <span id="total-pages-display" class="font-medium text-neutral-700">0</span>
                                <span class="text-neutral-500 ml-1">页</span>
                            </div>
                            
                            <button id="next-pdf-btn" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 font-medium transition-all duration-300 hover:shadow-lg hover:-translate-y-1 disabled:opacity-50 disabled:cursor-not-allowed flex items-center" disabled>
                                下一页 →
                            </button>
                        </div>
                    </div>
                    
                    <!-- 右侧：答题卡区域 -->
                    <div class="md:w-1/4">
                        <div class="flex justify-between items-center mb-6">
                            <div class="flex items-center">
                                <span id="current-question" class="text-primary font-bold text-xl">1</span>
                                <span class="text-neutral-500 ml-1">/</span>
                                <span id="total-questions" class="text-neutral-500">20</span>
                            </div>
                            
                            <div class="flex items-center">
                                ⏱️
                                <span id="timer" class="font-medium text-neutral-700 ml-2">00:00</span>
                                <span id="current-question-time" class="ml-4 text-sm text-neutral-500">00:00</span>
                            </div>
                        </div>
                        <!-- 选项容器 - 横向排列 -->
                        <div id="options-container" class="flex flex-wrap gap-2 justify-center py-2">
                            <!-- 选项将在这里动态生成 -->
                        </div>
                        <div class="flex justify-between">
                            <button id="prev-btn" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 font-medium transition-all duration-300 hover:shadow-lg hover:-translate-y-1 disabled:opacity-50 disabled:cursor-not-allowed flex items-center">
                                ←上题
                            </button>    
                            <button id="next-btn" class="px-4 py-2 bg-primary text-white rounded-lg font-medium transition-all duration-300 hover:shadow-lg hover:-translate-y-1 flex items-center">
                                下题→
                            </button>
                            <button id="submit-btn" class="px-4 py-2 bg-red-500 text-white rounded-lg font-medium transition-all duration-300 hover:shadow-lg hover:-translate-y-1 flex items-center ml-2">
                                ✅交卷
                            </button>
                        </div>

                        <div id="answer-card-container" class="bg-neutral-50 rounded-xl p-6 sticky top-8">
                            <h3 class="font-bold text-neutral-700 mb-4 flex items-center">
                                📋 答题卡
                            </h3>
                            
                            <div class="mb-4">
                                <div class="flex justify-between mb-2">
                                    <span class="text-sm text-neutral-600">已答：<span id="answered-count" class="font-medium text-primary">0</span></span>
                                    <span class="text-sm text-neutral-600">未答：<span id="unanswered-count" class="font-medium text-neutral-500">20</span></span>
                                </div>
                                <div class="w-full bg-neutral-200 rounded-full h-2">
                                    <div id="answer-progress" class="bg-primary h-2 rounded-full" style="width: 0%"></div>
                                </div>
                            </div>
                            
                            <div id="answer-card" class="grid grid-cols-5 gap-2">
                                <!-- 答题卡项目将在这里动态生成 -->
                            </div>
                            
                            <div class="mt-6 flex flex-wrap gap-3 text-sm">
                                <div class="flex items-center">
                                    <span class="w-4 h-4 rounded-full bg-primary inline-block mr-2"></span>
                                    <span class="text-neutral-600">当前题</span>
                                </div>
                                <div class="flex items-center">
                                    <span class="w-4 h-4 rounded-full bg-primary/10 inline-block mr-2"></span>
                                    <span class="text-neutral-600">已答题</span>
                                </div>
                                <div class="flex items-center">
                                    <span class="w-4 h-4 rounded-full bg-neutral-100 inline-block mr-2"></span>
                                    <span class="text-neutral-600">未答题</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 结束界面 - 带解析功能 -->
            <div id="result-screen" class="hidden">
                <div class="flex flex-col md:flex-row gap-6">
                    <!-- 左侧：结果统计 -->
                    <div class="md:w-1/3">
                        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                            <h2 class="text-2xl font-bold text-neutral-700 mb-4">答题结果</h2>
                            <div class="space-y-3">
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">总题数：</span>
                                    <span id="result-total-questions" class="font-bold text-neutral-700">0</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">已答：</span>
                                    <span id="result-answered" class="font-bold text-primary">0</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">未答：</span>
                                    <span id="result-unanswered" class="font-bold text-neutral-500">0</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">做对：</span>
                                    <span id="result-correct" class="font-bold text-green-500">0</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">做错：</span>
                                    <span id="result-incorrect" class="font-bold text-red-500">0</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">正确率：</span>
                                    <span id="result-accuracy" class="font-bold text-primary">0%</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">总用时：</span>
                                    <span id="result-total-time" class="font-bold text-neutral-700">00:00</span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-neutral-600">平均每题用时：</span>
                                    <span id="result-avg-time" class="font-bold text-neutral-700">00:00</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧：解析界面 -->
                    <div class="md:w-2/3">
                        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                            <!-- 头部信息 -->
                            <div class="flex justify-between items-center mb-6">
                                <div class="flex items-center">
                                    <span id="review-question-number" class="text-primary font-bold text-xl">1</span>
                                    <span class="text-neutral-500 ml-1">/</span>
                                    <span id="review-total-questions" class="text-neutral-500">20</span>
                                </div>
                                
                                <div class="flex items-center">
                                    <span id="question-status" class="px-3 py-1 rounded-full text-sm font-medium"></span>
                                    <span id="question-time" class="ml-4 text-sm text-neutral-500"></span>
                                </div>
                            </div>

                            <!-- 判卷答题卡 -->
                            <div class="bg-white rounded-xl shadow-md p-6">
                                <h3 class="font-bold text-neutral-700 mb-4 flex items-center">
                                    📋 答题卡
                                </h3>
                                
                                <div class="mb-4">
                                    <div class="flex justify-between mb-2">
                                        <span class="text-sm text-neutral-600">已标记正确答案：<span id="review-correct-count" class="font-medium text-primary">0</span></span>
                                    </div>
                                    <div class="w-full bg-neutral-200 rounded-full h-2">
                                        <div id="review-progress" class="bg-primary h-2 rounded-full" style="width: 0%"></div>
                                    </div>
                                </div>
                                
                                <div id="review-answer-card" class="grid grid-cols-5 gap-2">
                                    <!-- 答题卡项目将在这里动态生成 -->
                                </div>
                            </div>
                            
                            <!-- 正确答案选择区 -->
                            <div class="grid grid-cols-2 gap-4 mb-6">
                                <div>
                                    <h4 class="font-medium text-neutral-700 mb-2">你的答案：</h4>
                                    <div id="user-answer" class="p-3 rounded-lg border border-neutral-200 min-h-16"></div>
                                </div>
                                <div>
                                    <h4 class="font-medium text-neutral-700 mb-2">正确答案：</h4>
                                    <div id="correct-answer" class="p-3 rounded-lg border border-neutral-200 min-h-16">
                                        <div class="flex flex-wrap gap-2">
                                            <button class="correct-answer-btn px-3 py-1 border border-neutral-300 rounded-lg text-neutral-700 hover:border-primary transition-all" data-answer="A">A</button>
                                            <button class="correct-answer-btn px-3 py-1 border border-neutral-300 rounded-lg text-neutral-700 hover:border-primary transition-all" data-answer="B">B</button>
                                            <button class="correct-answer-btn px-3 py-1 border border-neutral-300 rounded-lg text-neutral-700 hover:border-primary transition-all" data-answer="C">C</button>
                                            <button class="correct-answer-btn px-3 py-1 border border-neutral-300 rounded-lg text-neutral-700 hover:border-primary transition-all" data-answer="D">D</button>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 初始化PDF.js
        const pdfjsLib = window['pdfjs-dist/build/pdf'];
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'assets/js/pdf.worker.min.js';

        // 应用状态
        const state = {
            pdfDoc: null,
            currentPage: 1,
            totalPages: 0,
            totalQuestions: 20,
            startQuestion: 1,
            userAnswers: {},
            correctAnswers: {},
            questionTimes: {},
            startTime: null,
            timerInterval: null,
            currentQuestionTime: 0,
            currentQuestionTimeInterval: null,
            currentReviewQuestion: 1,
            markedCount: 0,
            currentMode: 'single', // 'single' 或 'batch'
            totalTimeUsed: 0,
        };

        // DOM元素
        const elements = {
            pdfUpload: document.getElementById('pdf-upload'),
            startBtn: document.getElementById('start-btn'),
            totalQuestionsInput: document.getElementById('total-questions-input'),
            startQuestionInput: document.getElementById('start-question-input'),
            startScreen: document.getElementById('start-screen'),
            quizScreen: document.getElementById('quiz-screen'),
            resultScreen: document.getElementById('result-screen'),
            pdfContainer: document.getElementById('pdf-container'),
            currentQuestion: document.getElementById('current-question'),
            totalQuestions: document.getElementById('total-questions'),
            timer: document.getElementById('timer'),
            currentQuestionTime: document.getElementById('current-question-time'),
            optionsContainer: document.getElementById('options-container'),
            prevBtn: document.getElementById('prev-btn'),
            nextBtn: document.getElementById('next-btn'),
            submitBtn: document.getElementById('submit-btn'),
            answerCard: document.getElementById('answer-card'),
            answeredCount: document.getElementById('answered-count'),
            unansweredCount: document.getElementById('unanswered-count'),
            answerProgress: document.getElementById('answer-progress'),
            prevPdfBtn: document.getElementById('prev-pdf-btn'),
            nextPdfBtn: document.getElementById('next-pdf-btn'),
            pageNumInput: document.getElementById('page-num-input'),
            totalPagesDisplay: document.getElementById('total-pages-display'),
            // 结果界面元素
            resultTotalQuestions: document.getElementById('result-total-questions'),
            resultAnswered: document.getElementById('result-answered'),
            resultUnanswered: document.getElementById('result-unanswered'),
            resultCorrect: document.getElementById('result-correct'),
            resultIncorrect: document.getElementById('result-incorrect'),
            resultAccuracy: document.getElementById('result-accuracy'),
            resultTotalTime: document.getElementById('result-total-time'),
            resultAvgTime: document.getElementById('result-avg-time'),
            reviewQuestionNumber: document.getElementById('review-question-number'),
            reviewTotalQuestions: document.getElementById('review-total-questions'),
            questionStatus: document.getElementById('question-status'),
            questionTime: document.getElementById('question-time'),
            userAnswer: document.getElementById('user-answer'),
            correctAnswer: document.getElementById('correct-answer'),
            reviewAnswerCard: document.getElementById('review-answer-card'),
            reviewCorrectCount: document.getElementById('review-correct-count'),
            reviewProgress: document.getElementById('review-progress'),
        };

        // PDF处理模块
        const pdfModule = {
            loadPdf(file) {
                if (!file) return;
                
                const fileReader = new FileReader();
                fileReader.onload = function() {
                    const typedArray = new Uint8Array(this.result);
                    pdfjsLib.getDocument(typedArray).promise.then(function(pdfDoc_) {
                        state.pdfDoc = pdfDoc_;
                        state.totalPages = pdfDoc_.numPages;
                        state.currentPage = 1;
                        elements.startBtn.disabled = false;
                        
                        // 更新页面显示
                        elements.pageNumInput.value = 1;
                        elements.totalPagesDisplay.textContent = state.totalPages;
                        
                        // 更新按钮状态
                        pdfModule.updateButtonStates();
                        
                        pdfModule.renderPage(1);
                    }).catch(function(error) {
                        console.error('加载PDF失败:', error);
                        alert('加载PDF失败，请尝试其他文件');
                    });
                };
                fileReader.readAsArrayBuffer(file);
            },
            
            renderPage(num, container = elements.pdfContainer) {
                container.innerHTML = '<div class="flex items-center justify-center h-full text-neutral-400"><span class="animate-spin mr-2">🔄</span>加载中...</div>';
                
                state.pdfDoc.getPage(num).then(function(page) {
                    const viewport = page.getViewport({ scale: 1.5 });
                    
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d');
                    canvas.height = viewport.height;
                    canvas.width = viewport.width;
                    canvas.className = 'editing-breathing-bg';
                    
                    container.innerHTML = '';
                    container.appendChild(canvas);
                    
                    const renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };
                    
                    const renderTask = page.render(renderContext);
                    renderTask.promise.then(function() {
                        // 页面渲染完成
                        if (container === elements.pdfContainer) {
                            state.currentPage = num;
                            elements.pageNumInput.value = num;
                            pdfModule.updateButtonStates();
                        }
                    });
                });
            },
            
            goToPrevPage() {
                if (state.currentPage > 1) {
                    pdfModule.renderPage(state.currentPage - 1);
                }
            },
            
            goToNextPage() {
                if (state.currentPage < state.totalPages) {
                    pdfModule.renderPage(state.currentPage + 1);
                }
            },
            
            goToPage() {
                const pageNum = parseInt(elements.pageNumInput.value);
                if (pageNum >= 1 && pageNum <= state.totalPages) {
                    pdfModule.renderPage(pageNum);
                } else {
                    alert(`请输入1到${state.totalPages}之间的页码`);
                    elements.pageNumInput.value = state.currentPage;
                }
            },
            
            updateButtonStates() {
                elements.prevPdfBtn.disabled = state.currentPage <= 1;
                elements.nextPdfBtn.disabled = state.currentPage >= state.totalPages;
            }
        };

        // 计时模块
        const timerModule = {
            startTimer() {
                state.startTime = new Date();
                state.timerInterval = setInterval(timerModule.updateTimer, 1000);
            },
            
            updateTimer() {
                const now = new Date();
                const diff = Math.floor((now - state.startTime) / 1000);
                state.totalTimeUsed = diff;
                const minutes = Math.floor(diff / 60).toString().padStart(2, '0');
                const seconds = (diff % 60).toString().padStart(2, '0');
                elements.timer.textContent = `${minutes}:${seconds}`;
            },
            
            startCurrentQuestionTimer() {
                if (state.currentQuestionTimeInterval) {
                    clearInterval(state.currentQuestionTimeInterval);
                }
                
                state.currentQuestionTime = 0;
                state.currentQuestionTimeInterval = setInterval(() => {
                    state.currentQuestionTime++;
                    const minutes = Math.floor(state.currentQuestionTime / 60).toString().padStart(2, '0');
                    const seconds = (state.currentQuestionTime % 60).toString().padStart(2, '0');
                    elements.currentQuestionTime.textContent = `${minutes}:${seconds}`;
                }, 1000);
            },
            
            stopTimers() {
                clearInterval(state.timerInterval);
                clearInterval(state.currentQuestionTimeInterval);
            },
            
            formatTime(seconds) {
                const minutes = Math.floor(seconds / 60).toString().padStart(2, '0');
                const secs = (seconds % 60).toString().padStart(2, '0');
                return `${minutes}:${secs}`;
            }
        };

        // 题目模块
        const quizModule = {
            startQuiz() {
                state.totalQuestions = parseInt(elements.totalQuestionsInput.value) || 20;
                state.startQuestion = parseInt(elements.startQuestionInput.value) || 1;
                
                // 初始化用户答案和用时记录
                for (let i = state.startQuestion; i < state.startQuestion + state.totalQuestions; i++) {
                    state.userAnswers[i] = null;
                    state.questionTimes[i] = 0;
                    state.correctAnswers[i] = null;
                }
                
                // 更新UI
                elements.currentQuestion.textContent = state.startQuestion;
                elements.totalQuestions.textContent = state.totalQuestions;
                elements.startScreen.classList.add('hidden');
                elements.quizScreen.classList.remove('hidden');
                
                // 渲染选项
                quizModule.renderOptions();
                
                // 渲染答题卡
                quizModule.renderAnswerCard();
                
                // 开始计时
                timerModule.startTimer();
                
                // 开始当前题计时
                timerModule.startCurrentQuestionTimer();
            },
            
            renderOptions() {
                elements.optionsContainer.innerHTML = '';
                const options = ['A', 'B', 'C', 'D'];
                
                options.forEach(option => {
                    const button = document.createElement('button');
                    button.className = 'transition-all duration-300 hover:shadow-lg hover:-translate-y-1 border border-neutral-200 hover:border-primary rounded-lg p-2 cursor-pointer flex items-center min-w-[60px] justify-center';
                    
                    if (state.userAnswers[parseInt(elements.currentQuestion.textContent)] === option) {
                        button.classList.add('bg-primary/10', 'border-primary');
                    }
                    
                    button.textContent = option;
                    button.addEventListener('click', () => quizModule.selectOption(option));
                    elements.optionsContainer.appendChild(button);
                });
            },
            
            selectOption(option) {
                const currentQuestion = parseInt(elements.currentQuestion.textContent);
                state.userAnswers[currentQuestion] = option;
                state.questionTimes[currentQuestion] = state.currentQuestionTime;
                
                // 更新UI
                quizModule.renderOptions();
                quizModule.renderAnswerCard();
            },
            
            renderAnswerCard() {
                elements.answerCard.innerHTML = '';
                
                for (let i = state.startQuestion; i < state.startQuestion + state.totalQuestions; i++) {
                    const item = document.createElement('div');
                    item.className = 'w-10 h-10 rounded-lg flex items-center justify-center font-medium cursor-pointer transition-all duration-200 text-sm';
                    
                    const currentQuestion = parseInt(elements.currentQuestion.textContent);
                    
                    // 显示题号+答案（如20A）
                    if (state.userAnswers[i] !== null) {
                        item.textContent = `${i}${state.userAnswers[i]}`;
                    } else {
                        item.textContent = i;
                    }
                    
                    // 设置样式
                    if (i === currentQuestion) {
                        item.classList.add('bg-primary', 'text-white', 'border', 'border-primary', 'hover:bg-primary/90');
                    } else if (state.userAnswers[i] !== null) {
                        item.classList.add('bg-primary/10', 'text-primary', 'border', 'border-primary/30', 'hover:bg-primary/20');
                    } else {
                        item.classList.add('bg-neutral-100', 'text-neutral-500', 'border', 'border-neutral-200', 'hover:border-primary', 'hover:bg-primary/5');
                    }
                    
                    item.addEventListener('click', () => quizModule.goToQuestion(i));
                    elements.answerCard.appendChild(item);
                }
                
                // 更新已答/未答计数
                const answeredCount = Object.values(state.userAnswers).filter(answer => answer !== null).length;
                const unansweredCount = state.totalQuestions - answeredCount;
                
                elements.answeredCount.textContent = answeredCount;
                elements.unansweredCount.textContent = unansweredCount;
                elements.answerProgress.style.width = `${(answeredCount / state.totalQuestions) * 100}%`;
                
                // 更新按钮状态
                elements.prevBtn.disabled = parseInt(elements.currentQuestion.textContent) <= state.startQuestion;
                elements.nextBtn.disabled = parseInt(elements.currentQuestion.textContent) >= state.startQuestion + state.totalQuestions - 1;
            },
            
            goToPrevQuestion() {
                const currentQuestion = parseInt(elements.currentQuestion.textContent);
                if (currentQuestion > state.startQuestion) {
                    quizModule.goToQuestion(currentQuestion - 1);
                }
            },
            
            goToNextQuestion() {
                const currentQuestion = parseInt(elements.currentQuestion.textContent);
                if (currentQuestion < state.startQuestion + state.totalQuestions - 1) {
                    quizModule.goToQuestion(currentQuestion + 1);
                }
            },
            
            goToQuestion(questionNumber) {
                // 保存当前题目的用时
                const currentQuestion = parseInt(elements.currentQuestion.textContent);
                state.questionTimes[currentQuestion] = state.currentQuestionTime;
                
                // 更新当前题目
                elements.currentQuestion.textContent = questionNumber;
                
                // 重置当前题计时器
                timerModule.startCurrentQuestionTimer();
                
                // 更新UI
                quizModule.renderOptions();
                quizModule.renderAnswerCard();
            },
            
            submitQuiz() {
                // 保存最后一题的用时
                const currentQuestion = parseInt(elements.currentQuestion.textContent);
                state.questionTimes[currentQuestion] = state.currentQuestionTime;

                // 停止计时器
                timerModule.stopTimers();

                // 计算结果
                quizModule.calculateResults();

                // 更新UI
                elements.quizScreen.classList.add('hidden');
                elements.resultScreen.classList.remove('hidden');
                
                // 初始化解析界面
                reviewModule.initReview();
            },
            
            calculateResults() {
                let answeredCount = 0;
                let correctCount = 0;
                
                for (let i = state.startQuestion; i < state.startQuestion + state.totalQuestions; i++) {
                    if (state.userAnswers[i] !== null) {
                        answeredCount++;
                        if (state.correctAnswers[i] && state.userAnswers[i] === state.correctAnswers[i]) {
                            correctCount++;
                        }
                    }
                }
                
                // 计算总用时和平均用时
                let totalTime = 0;
                for (let i = state.startQuestion; i < state.startQuestion + state.totalQuestions; i++) {
                    totalTime += state.questionTimes[i];
                }
                const avgTime = answeredCount > 0 ? Math.floor(totalTime / answeredCount) : 0;
                
                // 更新结果界面
                elements.resultTotalQuestions.textContent = state.totalQuestions;
                elements.resultAnswered.textContent = answeredCount;
                elements.resultUnanswered.textContent = state.totalQuestions - answeredCount;
                elements.resultCorrect.textContent = correctCount;
                elements.resultIncorrect.textContent = answeredCount - correctCount;
                elements.resultAccuracy.textContent = answeredCount > 0 ? `${Math.round((correctCount / answeredCount) * 100)}%` : '0%';
                elements.resultTotalTime.textContent = timerModule.formatTime(state.totalTimeUsed);
                elements.resultAvgTime.textContent = timerModule.formatTime(avgTime);
            },
            
            restartQuiz() {
                // 重置状态
                state.pdfDoc = null;
                state.currentPage = 1;
                state.totalPages = 0;
                state.totalQuestions = 20;
                state.startQuestion = 1;
                state.userAnswers = {};
                state.correctAnswers = {};
                state.questionTimes = {};
                state.startTime = null;
                state.timerInterval = null;
                state.currentQuestionTime = 0;
                state.currentQuestionTimeInterval = null;
                state.currentReviewQuestion = 1;
                state.markedCount = 0;
                state.currentMode = 'single';
                state.totalTimeUsed = 0;

                // 重置UI
                elements.pdfUpload.value = '';
                elements.totalQuestionsInput.value = 20;
                elements.startQuestionInput.value = 1;
                elements.startBtn.disabled = true;
                elements.resultScreen.classList.add('hidden');
                elements.startScreen.classList.remove('hidden');
                elements.pdfContainer.innerHTML = '<div class="flex items-center justify-center h-full text-neutral-400"><span class="animate-spin mr-2">🔄</span>加载中...</div>';
            }
        };

        // 解析模块
        const reviewModule = {
            initReview() {
                state.currentReviewQuestion = state.startQuestion;
                elements.reviewQuestionNumber.textContent = state.currentReviewQuestion;
                elements.reviewTotalQuestions.textContent = state.totalQuestions;
                
                // 渲染解析界面
                reviewModule.renderReviewPage();
                reviewModule.renderReviewAnswerCard();
                
                // 初始化正确答案按钮事件
                document.querySelectorAll('.correct-answer-btn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const answer = e.target.dataset.answer;
                        const currentQuestion = state.currentReviewQuestion;
                        state.correctAnswers[currentQuestion] = answer;
                        reviewModule.renderReviewPage();
                        reviewModule.renderReviewAnswerCard();
                        quizModule.calculateResults();
                    });
                });
            },
            
            renderReviewPage() {
                const currentQuestion = state.currentReviewQuestion;
                const userAnswer = state.userAnswers[currentQuestion];
                const correctAnswer = state.correctAnswers[currentQuestion];
                
                // 更新问题状态
                if (correctAnswer === null) {
                    elements.questionStatus.textContent = '未设置正确答案';
                    elements.questionStatus.className = 'px-3 py-1 rounded-full text-sm font-medium bg-neutral-100 text-neutral-600';
                } else if (userAnswer === correctAnswer) {
                    elements.questionStatus.textContent = '回答正确';
                    elements.questionStatus.className = 'px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-600';
                } else {
                    elements.questionStatus.textContent = '回答错误';
                    elements.questionStatus.className = 'px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-600';
                }
                
                // 更新用时
                elements.questionTime.textContent = `用时: ${timerModule.formatTime(state.questionTimes[currentQuestion])}`;
                
                
                // 更新用户答案显示
                elements.userAnswer.textContent = userAnswer || '未作答';
                if (userAnswer && correctAnswer && userAnswer === correctAnswer) {
                    elements.userAnswer.className = 'p-3 rounded-lg border border-green-300 bg-green-50 min-h-16';
                } else if (userAnswer && correctAnswer && userAnswer !== correctAnswer) {
                    elements.userAnswer.className = 'p-3 rounded-lg border border-red-300 bg-red-50 min-h-16';
                } else {
                    elements.userAnswer.className = 'p-3 rounded-lg border border-neutral-200 min-h-16';
                }
                
                // 更新正确答案显示和按钮状态
                elements.correctAnswer.innerHTML = '';
                const options = ['A', 'B', 'C', 'D'];
                
                options.forEach(option => {
                    const button = document.createElement('button');
                    button.className = `px-3 py-1 border rounded-lg text-neutral-700 transition-all duration-200 hover:shadow-md ${
                        correctAnswer === option 
                            ? 'bg-primary/10 border-primary text-primary font-medium' 
                            : 'border-neutral-300 hover:border-primary'
                    }`;
                    
                    button.textContent = option;
                    button.dataset.answer = option;
                    button.addEventListener('click', () => {
                        state.correctAnswers[currentQuestion] = option;
                        reviewModule.renderReviewPage();
                        reviewModule.renderReviewAnswerCard();
                        quizModule.calculateResults();
                    });
                    
                    elements.correctAnswer.appendChild(button);
                });
                
            },
            
            renderReviewAnswerCard() {
                elements.reviewAnswerCard.innerHTML = '';
                state.markedCount = 0;
                
                for (let i = state.startQuestion; i < state.startQuestion + state.totalQuestions; i++) {
                    const item = document.createElement('div');
                    item.className = 'w-10 h-10 rounded-lg flex items-center justify-center font-medium cursor-pointer transition-all duration-200 text-sm';
                    
                    const userAnswer = state.userAnswers[i];
                    const correctAnswer = state.correctAnswers[i];
                    
                    // 显示题号+答案（如20A）
                    if (userAnswer !== null) {
                        item.textContent = `${i}${userAnswer}`;
                    } else {
                        item.textContent = i;
                    }
                    
                    // 设置样式
                    if (i === state.currentReviewQuestion) {
                        item.classList.add('bg-primary', 'text-white', 'border', 'border-primary', 'hover:bg-primary/90');
                    } else if (correctAnswer !== null) {
                        // 已设置正确答案
                        state.markedCount++;
                        if (userAnswer === correctAnswer) {
                            item.classList.add('bg-green-100', 'text-green-600', 'border', 'border-green-200', 'hover:bg-green-200');
                        } else if (userAnswer === null) {
                            item.classList.add('bg-neutral-100', 'text-neutral-500', 'border', 'border-neutral-200', 'hover:border-primary', 'hover:bg-primary/5');
                        } else {
                            item.classList.add('bg-red-100', 'text-red-600', 'border', 'border-red-200', 'hover:bg-red-200');
                        }
                    } else {
                        // 未设置正确答案
                        if (userAnswer !== null) {
                            item.classList.add('bg-primary/10', 'text-primary', 'border', 'border-primary/30', 'hover:bg-primary/20');
                        } else {
                            item.classList.add('bg-neutral-100', 'text-neutral-500', 'border', 'border-neutral-200', 'hover:border-primary', 'hover:bg-primary/5');
                        }
                    }
                    
                    item.addEventListener('click', () => {
                        state.currentReviewQuestion = i;
                        reviewModule.renderReviewPage();
                    });
                    elements.reviewAnswerCard.appendChild(item);
                }
                
                // 更新已标记正确答案计数
                elements.reviewCorrectCount.textContent = state.markedCount;
                elements.reviewProgress.style.width = `${(state.markedCount / state.totalQuestions) * 100}%`;
            },
            
            goToPrevReviewQuestion() {
                if (state.currentReviewQuestion > state.startQuestion) {
                    state.currentReviewQuestion--;
                    reviewModule.renderReviewPage();
                }
            },
            
            goToNextReviewQuestion() {
                if (state.currentReviewQuestion < state.startQuestion + state.totalQuestions - 1) {
                    state.currentReviewQuestion++;
                    reviewModule.renderReviewPage();
                }
            }
        };

        // 初始化事件监听器
        function initEventListeners() {
            // PDF上传
            elements.pdfUpload.addEventListener('change', (e) => pdfModule.loadPdf(e.target.files[0]));
            
            // 开始按钮
            elements.startBtn.addEventListener('click', quizModule.startQuiz);
            
            // 上一题/下一题/交卷按钮
            elements.prevBtn.addEventListener('click', quizModule.goToPrevQuestion);
            elements.nextBtn.addEventListener('click', quizModule.goToNextQuestion);
            elements.submitBtn.addEventListener('click', quizModule.submitQuiz);
            
            // PDF翻页控制按钮
            elements.prevPdfBtn.addEventListener('click', pdfModule.goToPrevPage);
            elements.nextPdfBtn.addEventListener('click', pdfModule.goToNextPage);
            elements.pageNumInput.addEventListener('change', pdfModule.goToPage);
            elements.pageNumInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    pdfModule.goToPage();
                }
            });
             
        }

        // 初始化应用
        function initApp() {
            initEventListeners();
        }

        // 当DOM加载完成后初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>